package com.example.demo.job;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

@Component
public class DynamicScheduler implements SchedulingConfigurer {

    private ScheduledTaskRegistrar taskRegistrar;
    private final Map<String, ScheduledFuture<?>> taskMap = new ConcurrentHashMap<>();

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        this.taskRegistrar = taskRegistrar;

    }

//    @PostConstruct
    public void intt(){
        new Thread(()-> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            addOrUpdateTask("77",a->{
                System.out.println("a = " + a);
            },77,"0/10 * * * * ? ");
        }).start();
//        addOrUpdateTask("77",()-> System.out.println(11),"0/10 * * * * ? ");
    }
    // 添加/更新任务
    public <T> void addOrUpdateTask(String taskId, Consumer<T>  task, T param,String cronExpression) {
        // 先取消已有任务
        cancelTask(taskId);
        
        // 添加新任务
        ScheduledFuture<?> future = taskRegistrar.getScheduler().schedule(
            ()->task.accept(param),
            new CronTrigger(cronExpression)
        );
        taskMap.put(taskId, future);
    }

    // 取消任务
    public void cancelTask(String taskId) {
        ScheduledFuture<?> future = taskMap.get(taskId);
        if (future != null) {
            future.cancel(true);
            taskMap.remove(taskId);
        }
    }

    // 获取所有任务ID
    public Set<String> getTaskIds() {
        return taskMap.keySet();
    }
}